import store from '@/store'

let mutationObserver
export default {
  auth: {
    mounted: function (el, binding, vnode) {
      if (!store.userApp.permissionList.some((v: string) => v === binding.value)) {
        const comment = document.createComment(' ')
        Object.defineProperty(comment, 'setAttribute', {
          value: () => undefined
        })
        vnode.elm = comment
        vnode.text = ' '
        vnode.isComment = true
        el.parentNode.replaceChild(comment, el)
      }
    }
  },
  MutationObserver: {
    mounted: function (el, binding, vnode) {
      const MutationObserver =
        window.MutationObserver || window.webkitMutationObserver || window.MozMutationObserver
      mutationObserver = new MutationObserver(function (mutations) {
        console.log(mutations)

        const types = ['childList', 'attributes', 'characterData']
        const arg = binding.arg
        if (arg && types.includes(arg)) {
          // 参数存在 执行参数类型的回调
          mutations.map((v) => {
            if (v.type === arg) {
              binding.value(el)
            }
          })
        } else {
          // 参数不存在 执行全部回调
          binding.value(el)
        }
      })
      mutationObserver.observe(el, {
        subtree: true,
        attributes: true,
        childList: true,
        characterData: true
      })
    },
    unmounted: function (el) {
      mutationObserver.disconnect()
    }
  },
  visibleRender: (el, binding) => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          // 当元素进入视窗时
          if (binding.value) {
            binding.value('enter')
          }
          if (binding.arg && binding.arg === 'enter') {
            observer.unobserve(el) // 停止观察
          }
        } else {
          if (binding.value) {
            binding.value('leave')
          }
          if (binding.arg && binding.arg === 'leave') {
            observer.unobserve(el) // 停止观察
          }
        }
      },
      {
        rootMargin: '50px',
        threshold: 0.1
      }
    )

    observer.observe(el) // 开始观察元素
  },
  resizeObserver: (el, binding) => {
    const observer = new ResizeObserver((entries) => {
      binding.value(entries[0].target.clientHeight)
    })

    observer.observe(el)
  }
}
